package org.cloud.automatic.queue.job;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.cloud.automatic.queue.entity.SendQueueWorkerBO;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;


@Slf4j
@Data
public abstract class Worker implements Runnable {
	
	/**
	 * 任务队列
	 */
	protected ConcurrentLinkedQueue<SendQueueWorkerBO> workQueue ;

	/**
	 * 终止任务通知标识
	 */
    protected ConcurrentHashMap<String, String> noticeComplatedMap;

	/**
	 * 任务执行抽象方法。由具体的Worker实现者根据实际需要实现此方法。
	 * @param data
	 */
	public abstract void handle(SendQueueWorkerBO data);
	
	@Override
	public void run() {

		while(true){
			
			if(workQueue.size() == 0 && isComplated()){
			    log.info("===队列补偿本轮执行完成===");
				break ;
			}
			
			SendQueueWorkerBO data = workQueue.poll();
			if(data == null){
				try {
					Thread.currentThread().sleep(1);
				} catch (InterruptedException e) {
					log.warn("事务补偿队列异常", e);
					Thread.currentThread().interrupt();
				}
				continue ;
			}
			
			handle(data);
		}
	}
	
	/**
	 * 通过通知集合引用获取通知，如果该集合不为空，则终止所有任务的执行
	 * @return
	 */
	public boolean isComplated(){
		if(noticeComplatedMap != null && this.noticeComplatedMap.size() > 0){
			return true;
		}
		return false;
	}

}
